package com.jx.mlxg.service.impl;

<<<<<<< HEAD
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jx.mlxg.entity.Users;
import com.jx.mlxg.mapper.OrdersMapper;
import com.jx.mlxg.service.UsersService;
import com.jx.mlxg.mapper.UsersMapper;
import com.jx.mlxg.utils.HttpClientUtil;
import com.jx.mlxg.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
=======
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jx.mlxg.entity.Users;
import com.jx.mlxg.service.UsersService;
import com.jx.mlxg.mapper.UsersMapper;
import org.springframework.stereotype.Service;
>>>>>>> eb72a42842a7e02f996c4f2d21dc4051aa14ecf1

/**
* @author Administrator
* @description 针对表【users】的数据库操作Service实现
* @createDate 2025-02-21 13:54:00
*/
@Service
<<<<<<< HEAD
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    /**
     * 微信 auth.code2Session 接口
     */
    private final String WECHAT_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    public Users findOrCreateUser(String phoneNumber) {
        // 使用 LambdaQueryWrapper 查询用户
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getPhoneNumber, phoneNumber);

        Users user = usersMapper.selectOne(queryWrapper);

        if (user == null) {
            // 如果用户不存在，创建新用户

            user = new Users();
            user.setPhoneNumber(phoneNumber);
            usersMapper.insert(user);
        }
        return user;
    }


    @Override
    public Map<String, Object> getUserInfoAndOrderStatistics(int userId) {
        Map<String, Object> result = new HashMap<>();

        // 查询用户的基本信息（假设用户名存储在users表中）
        // 这里需要根据实际的用户表结构进行查询
        String username = "王纪新"; // 示例用户名，实际应从数据库查询

        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getUserId, userId);
        Users users = usersMapper.selectOne(queryWrapper);

        username = users.getUsername();
        // 查询订单统计信息
        List<Map<String, Object>> statistics = ordersMapper.getOrderStatisticsByUserId(userId);

        // 查询总购买数量
        int totalBoughtCount = ordersMapper.getTotalBoughtCountByUserId(userId);

        // 构造返回数据
        result.put("username", username);
        result.put("hasBoughtCount", totalBoughtCount);

        List<Map<String, String>> formattedStatistics = new ArrayList<>();
        for (Map<String, Object> stat : statistics) {
            List<Map<String, String>> statistics1 = (List<Map<String, String>>) stat.get("statistics");
            for (Map<String, String> stat1 : statistics1) {
                Map<String, String> formattedStat = new HashMap<>();
                formattedStat.put("title", stat1.get("title").toString());
                formattedStat.put("content", stat1.get("content").toString());
                formattedStatistics.add(formattedStat);
            }

        }

        result.put("statistics", formattedStatistics);
        result.put("commonOperations", new String[]{"receiverAddress"});

        return result;
    }


    @Override
    public int getUserIdByPhoneNumber(String phoneNumber) {
        return usersMapper.getUserIdByPhoneNumber(phoneNumber);
    }

    @Override
    public Users findByPhoneNumber(String phoneNumber) {
        return getOne(new QueryWrapper<Users>().eq("phone_number", phoneNumber));
    }

    @Override
    public Map<String, Object> authWechat(String code,String phoneCode) {
        // 获取 openid
        String openId = getOpenId(code);

        // 查询用户是否已存在
        Integer userId = usersMapper.getUserByOpenId(openId);

        String token = JwtUtil.genToken(openId);

        if (userId == null) {
            // 如果用户不存在，则创建用户
            HashMap<String, String> maps = new HashMap<>();
            maps.put("appid", "wx3af54edceb6bf033");
            maps.put("secret", "fea51d3dffdbb35a8db8cbcf44d7ad4b");
            maps.put("grant_type", "client_credential");
            String json = HttpClientUtil.doGet("https://api.weixin.qq.com/cgi-bin/token",maps);
            System.out.println("json---->"+json);
            JSONObject jsonObject = JSON.parseObject(json);
            // 从JSONObject中获取openid并返回
            String accessToken = jsonObject.getString("access_token");
            //通过token和code来获取用户手机号
            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;
            //封装请求体
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("code", phoneCode);
            try {
                String post4Json = HttpClientUtil.doPost4Json(url, paramMap);
                System.out.println("post4Json--->" + post4Json);

// 解析 JSON 数据
                JSONObject post4JsonObject = JSON.parseObject(post4Json);

// 安全地提取 phone_info 对象
                JSONObject phoneInfo = post4JsonObject.getJSONObject("phone_info");
                if (phoneInfo != null) {
                    // 从 phone_info 中提取 phoneNumber
                    String phoneNumber = phoneInfo.getString("phoneNumber");
                    if (phoneNumber != null) {
                        System.out.println("phoneNumber: " + phoneNumber);
                        Users users = new Users();
                        users.setPhoneNumber(phoneNumber);
                        users.setUsername(phoneNumber);
                        users.setOpenId(openId);
                        users.setCreatedAt(LocalDateTime.now());
                        users.setRole(3);//开发者0 董事长1 管理员2 普通用户3
//            Users users = Users.builder().openId(openId).createTime(LocalDateTime.now()).build();
                        usersMapper.insert(users);

                        HashMap<String, Object> map = new HashMap<>();
                        map.put("userId",users.getUserId());
                        map.put("token", token);
                        return map;
                    } else {
                        System.out.println("phoneNumber 字段不存在或为空");
                    }
                } else {
                    System.out.println("phone_info 对象不存在或为空");
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        // 用户已存在
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("userId",userId);
        map1.put("token", token);
        return map1;
    }

    @Override
    public Users findByOpenId(String openId) {
        QueryWrapper<Users> open_id = new QueryWrapper<Users>().eq("openid", openId);
        return usersMapper.selectOne(open_id);
    }


    /**
     * 通过微信登录code获取openId
     *
     * @param code 微信登录code
     * @return openId
     */
    public String getOpenId(String code) {
        // 添加参数
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", "wx3af54edceb6bf033");
        map.put("secret", "fea51d3dffdbb35a8db8cbcf44d7ad4b");
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        // 使用封装好的HttpClientUtil工具类发送请求
        String json = HttpClientUtil.doGet(WECHAT_LOGIN_URL, map);
        // 将JSON字符串转换为JSONObject对象
        JSONObject jsonObject = JSON.parseObject(json);
        // 从JSONObject中获取openid并返回
        return jsonObject.getString("openid");
    }


}

=======
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
    implements UsersService{

}




>>>>>>> eb72a42842a7e02f996c4f2d21dc4051aa14ecf1
